import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_app/app/app_state.dart';
import 'package:flutter_app/bean/user_info.dart';
import 'package:flutter_app/compents/dialog_util.dart';
import 'package:flutter_app/controller/base/base_getx_controller.dart';
import 'package:flutter_app/defualt/Global.dart';
import 'package:flutter_app/http/http_manager.dart';
import 'package:flutter_app/theme/app_text.dart';
import 'package:get/get.dart';

class LoginController extends BaseGetXController {
  //AutovalidateMode用于配置[FormField]和[Form]小部件的自动验证。
  var autovalidateMode = AutovalidateMode.disabled.obs;
  var isObscure = true.obs;
  var isShowClearIcon = false.obs;

  //编辑文本字段创建一个控制器
  TextEditingController userNameController = TextEditingController();
  TextEditingController userPwdController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    userNameController.addListener(() {
      isShowClearIcon.value = userNameController.text.isNotEmpty;
    });
  }

  void clearText() {
    userNameController.text = "";
  }

  ///设置当前密码是否可见，false可见，true不可见
  void setObscure(bool obscure) {
    isObscure.value = obscure;
  }

  ///设置当前自动验证模式
  void setAutovalidateMode(AutovalidateMode mode) {
    autovalidateMode.value = mode;
  }

  ///提交登录
  void submitForm() {
    LoadingDialog.show(message: KText.loadingText);
    //提交登录请求
    handleRequest(
        HttpManager.instance.postFormData("user/login", {
          "username": userNameController.text.trim(),
          "password": userPwdController.text.trim()
        }),
        true, (value) {
      var user = UserData.fromJson(value).data;
      //登录成功后，记录账号密码
      user.setUserPassword(userPwdController.text.trim());
      Global.saveUserProfile(user);
      Get.find<AppState>().loginState.value = LoginState.LOGIN;
      List<Cookie> cookies = [
        Cookie("loginUserName", userNameController.text.trim()),
        Cookie("loginUserPassword", userPwdController.text.trim())
      ];
      HttpManager.instance.addCookies(cookies);
      LoadingDialog.dismiss();
      //返回上一级页面，并返回结果
      Get.back();
    }, failure: (error) {
          LoadingDialog.dismiss();
          Get.snackbar("错误",error,backgroundColor:Colors.red,colorText: Colors.white);
    });
  }
}
